package fu.capstone.hanoicityguide.presentation.fragment.food;

import org.mapsforge.core.model.LatLong;
import org.mapsforge.map.android.view.MapView;
import org.mapsforge.map.layer.Layers;
import org.mapsforge.map.layer.overlay.Marker;

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import fu.capstone.hanoicityguide.R;
import fu.capstone.hanoicityguide.business.bo.food.FoodBO;
import fu.capstone.hanoicityguide.business.bo.food.FoodBOImp;
import fu.capstone.hanoicityguide.business.model.Food;
import fu.capstone.hanoicityguide.common.offlinemapultility.OfflineMapUtil;
import fu.capstone.hanoicityguide.common.utility.LocationSetting;

public class FoodOfflineMapFragment extends Fragment {

	private OfflineMapUtil util;
	private MapView mapview;
	private FoodBO foodBO;
	private Food food;
	private LatLong food_geo;
	private LocationSetting locationSetting;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View foodOfflineMapFragment = inflater.inflate(
				R.layout.offline_map_fragment, container, false);

		try {
			util = new OfflineMapUtil(container.getContext());
			mapview = (MapView) foodOfflineMapFragment
					.findViewById(R.id.mapView);

			Bundle bundle = this.getArguments();
			int foodID = bundle.getInt("FoodID", 0);
			if (foodID != 0) {

				foodBO = new FoodBOImp(container.getContext());
				food = foodBO.browseFood(foodID);
				food_geo = util.convertGeoCoordinateToLatLong(food.getGeo());
			}

			/* Setup map and create markers */
			locationSetting = new LocationSetting(container.getContext());
			if (locationSetting.getGPSSetting(container.getContext())) {
				util.setupofflinemap(mapview, container.getContext());
				Marker placeMarker = util.createMarker(container.getContext(),
						food_geo, food.getName(), "");
				LatLong mylocation = util.getcurrentLocation(
						container.getContext(), mapview);

				Marker mylocationMarker = util.createMyLocationMarker(
						container.getContext(), mylocation,
						R.drawable.mylocationmarker);

				Layers layers = this.mapview.getLayerManager().getLayers();
				layers.add(placeMarker);
				layers.add(mylocationMarker);

				/* routing */
				util.initHopper();
				util.calcPath(mylocation.latitude, mylocation.longitude,
						food_geo.latitude, food_geo.longitude, mapview);

			} else {
				locationSetting.showSettingsAlert();
			}
		} catch (Exception e) {
			Log.v("Food offline map", "routing");
		}

		return foodOfflineMapFragment;
	}

}
